package com.dminvoicemanager;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
//import com.itextpdf.license.LicenseKey;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class DM_PDF_Viewer extends Activity {

	private static final String LOG_TAG = "GeneratePDF";
	private static final String TAG = null;
	private EditText preparedBy;
	private File pdfFile;
	private String filename;
	private String filepath = "MyInvoices";
	private BaseFont bfBold;
	private Button b;
	private String DBNAME = "dminvoicemanager.db";
	private SQLiteDatabase mydb;
	// Main Invoice
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_pdf_viewer);
		
		
		filename = getAddDateTimeString().toString() + ".pdf";
		preparedBy = (EditText) findViewById(R.id.preparedBy);
		preparedBy.setText(filename);
		if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
			Log.v(LOG_TAG,
					"External Storage not available or you don't have permission to write");
		} else {
			// path for the PDF file in the external storage
			pdfFile = new File(getExternalFilesDir(filepath), filename);
			Log.v(TAG, "pdfFile Path :"+ pdfFile);
		}
	}

	public void printPDF(View v) {

		switch (v.getId()) {

		// start the process of creating the PDF and then print it
		case R.id.printPDF:
			String reportinvName = preparedBy.getText().toString();
			generatePDF(reportinvName);
			break;

		}

	}

	private void generatePDF(String reportinvName) {

		// create a new document
		Document document = new Document();

		try {
			
			PdfWriter docWriter = PdfWriter.getInstance(document,
					new FileOutputStream(pdfFile));
			document.open();

			PdfContentByte cb = docWriter.getDirectContent();
			// initialize fonts for text printing
			initializeFonts();

			// the company logo is stored in the assets which is read only
			// get the logo and print on the document
			InputStream inputStream = getAssets().open("olympic_logo.png");
			Bitmap bmp = BitmapFactory.decodeStream(inputStream);
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
			Image companyLogo = Image.getInstance(stream.toByteArray());
			companyLogo.setAbsolutePosition(25, 700);
			companyLogo.scalePercent(25);
			document.add(companyLogo);

			// creating a sample invoice with some customer data
			createHeadings(cb, 400, 780, "Maliban Biscuits(Pvt) Ltd.");
			createHeadings(cb, 400, 770, "#389,Galle road");
			createHeadings(cb, 400, 760, "Ratmalana-12500");
			createHeadings(cb, 400, 750, "Western Province");
			createHeadings(cb, 400, 740, "Sri Lanka");
			createHeadings(cb, 400, 730, "Tel: 011 5 555000");

			// list all the products sold to the customer
			float[] columnWidths = { 1f, 6f, 6f, 10f, 2f, 2f, 3f };
			// create PDF table with the given widths
			PdfPTable table = new PdfPTable(columnWidths);
			// set table width a percentage of the page width
			table.setTotalWidth(500f);

			PdfPCell cell = new PdfPCell(new Phrase("ID"));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
			cell = new PdfPCell(new Phrase("REF NO"));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
			cell = new PdfPCell(new Phrase("ITEM CODE"));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
			cell = new PdfPCell(new Phrase("ITEM DESCRIPTION"));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
			cell = new PdfPCell(new Phrase("CS"));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
			cell = new PdfPCell(new Phrase("PS"));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
			cell = new PdfPCell(new Phrase("AMT"));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
			table.setHeaderRows(1);

			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			// invoice header
			Cursor selectInvHeadDetails = null;
			try {
				String query = "SELECT FH.RefNo,FH.TxnDate,FH.RepCode,FH.DebCode,FH.LocCode,FH.TotalAmt,FH.TotalDis,FD.SeqNo,FD.Itemcode,FD.CaseQty,FD.PiceQty,FD.Amt,FD.itemDescription from FinvHed FH,FinvDet FD Where FH.RefNo = FD.RefNo";
				selectInvHeadDetails = mydb.rawQuery(query, null);
			} catch (Exception e) {
			}
			if (selectInvHeadDetails != null) {
				if (selectInvHeadDetails.getCount() > 0) {
					while (selectInvHeadDetails.moveToNext()) {
						// FH.RefNo,FH.TxnDate,FH.RepCode,FH.DebCode,FH.LocCode,FH.TotalAmt,FH.TotalDis,
						// FD.SeqNo,FD.Itemcode,FD.CaseQty,FD.PiceQty,FD.Amt,FD.itemDescription
						String RefNo = selectInvHeadDetails.getString(0);
						String TxnDate = selectInvHeadDetails.getString(1);
						String RepCode = selectInvHeadDetails.getString(2);
						String DebCode = selectInvHeadDetails.getString(3);
						String LocCode = selectInvHeadDetails.getString(4);
						String SeqNo = selectInvHeadDetails.getString(7);
						String Itemcode = selectInvHeadDetails.getString(8);
						String CaseQty = selectInvHeadDetails.getString(9);
						String PiceQty = selectInvHeadDetails.getString(10);
						String Amt = selectInvHeadDetails.getString(11);
						String itemDescription = selectInvHeadDetails
								.getString(12);

						table.addCell(SeqNo);
						table.addCell(RefNo);
						table.addCell(Itemcode);
						table.addCell(itemDescription);
						table.addCell(CaseQty);
						table.addCell(PiceQty);
						table.addCell(Amt);
						Log.e("RefNo", "RefNo :" + RefNo);
					}
				} else {
					Log.e("PDFCreator 9999999", "Empty Record Set");
					// PrintSummary = "Empty Records Print";
				}
			}
			selectInvHeadDetails.close();
			mydb.close();
			// absolute location to print the PDF table from
			table.writeSelectedRows(0, -1, document.leftMargin(), 650,
					docWriter.getDirectContent());

			// print the signature image along with the persons name
			inputStream = getAssets().open("signature.png");
			bmp = BitmapFactory.decodeStream(inputStream);
			stream = new ByteArrayOutputStream();
			bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
			Image signature = Image.getInstance(stream.toByteArray());
			signature.setAbsolutePosition(400f, 150f);
			signature.scalePercent(25f);
			document.add(signature);

			createHeadings(cb, 450, 135, reportinvName);

			document.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		// PDF file is now ready to be sent to the bluetooth printer using
		// PrintShare
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setPackage("com.dynamixsoftware.printershare");
		i.setDataAndType(Uri.fromFile(pdfFile), "application/pdf");
		startActivity(i);

	}

	private void createHeadings(PdfContentByte cb, float x, float y, String text) {

		cb.beginText();
		cb.setFontAndSize(bfBold, 6);
		cb.setTextMatrix(x, y);
		cb.showText(text.trim());
		cb.endText();

	}

	private static boolean isExternalStorageReadOnly() {
		String extStorageState = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
			return true;
		}
		return false;
	}

	private static boolean isExternalStorageAvailable() {
		String extStorageState = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
			return true;
		}
		return false;
	}

	private void initializeFonts() {

		try {
			bfBold = BaseFont.createFont(BaseFont.HELVETICA_BOLD,
					BaseFont.CP1252, BaseFont.EMBEDDED);
			

		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}
}
